package com.gwsdk.paysdk.Geetest;

import android.content.Context;
import android.os.AsyncTask;

import com.geetest.sdk.GT3ConfigBean;
import com.geetest.sdk.GT3ErrorBean;
import com.geetest.sdk.GT3GeetestUtils;
import com.geetest.sdk.GT3Listener;
import com.gwsdk.paysdk.config.GWConstant;
import com.gwsdk.paysdk.utils.GWLog;

import org.json.JSONException;
import org.json.JSONObject;


public class GeetestManager extends GT3Listener {

    private static final String TAG = "GeetestManager";
    private GT3GeetestUtils gt3GeetestUtils;
    private GT3ConfigBean gt3ConfigBean;

    private boolean isVerify;
    private GeetestResult result;
    private String geetest_challenge = "";
    private String geetest_validate = "";
    private String geetest_seccode = "";

    public String getGeetest_challenge() {
        return geetest_challenge;
    }

    public String getGeetest_validate() {
        return geetest_validate;
    }

    public String getGeetest_seccode() {
        return geetest_seccode;
    }

    public void setVerify(boolean verify) {
        isVerify = verify;
    }

    public boolean isVerify() {
        return isVerify;
    }

    private static GeetestManager instance;
    public static GeetestManager getInstance() {
        if (null == instance) {
            instance = new GeetestManager();
        }
        return instance;
    }


    private GeetestManager(){}

    public void init(Context context) {
        // 请在oncreate方法里初始化以获取足够手势数据来保证第一轮验证成功率
        gt3GeetestUtils = new GT3GeetestUtils(context);

        // 配置bean文件，也可在oncreate初始化
        gt3ConfigBean = new GT3ConfigBean();
        // 设置验证模式，1：bind，2：unbind
        gt3ConfigBean.setPattern(1);
        // 设置点击灰色区域是否消失，默认不消失
        gt3ConfigBean.setCanceledOnTouchOutside(false);
        // 设置语言，如果为null则使用系统默认语言
        gt3ConfigBean.setLang(null);
        // 设置加载webview超时时间，单位毫秒，默认10000，仅且webview加载静态文件超时，不包括之前的http请求
        gt3ConfigBean.setTimeout(10000);
        // 设置webview请求超时(用户点选或滑动完成，前端请求后端接口)，单位毫秒，默认10000
        gt3ConfigBean.setWebviewTimeout(10000);
        // 设置回调监听
        gt3ConfigBean.setListener(this);
        gt3GeetestUtils.init(gt3ConfigBean);
    }

    public void startCheck(GeetestResult callback) {
        this.result = callback;
        if (getInstance().isVerify){
            gt3GeetestUtils.startCustomFlow();
        }else {
            if (callback != null){
                callback.success();
            }
        }

    }

    /**
     * 验证码加载完成
     * @param duration 加载时间和版本等信息，为json格式
     */
    @Override
    public void onDialogReady(String duration) {
        GWLog.e(TAG, "GT3BaseListener-->onDialogReady-->" + duration);
    }

    /**
     * 图形验证结果回调
     * @param code 1为正常 0为失败
     */
    @Override
    public void onReceiveCaptchaCode(int code) {
        GWLog.e(TAG, "GT3BaseListener-->onReceiveCaptchaCode-->" + code);
    }

    /**
     * 自定义api2回调
     * @param result，api2请求上传参数
     *              {"geetest_challenge":"19f06a3e64fa00cc4fac7ba41922f87abb",
     *              "geetest_seccode":"ec14f45cc7b18669ae4e3ff2341b13ea|jordan",
     *              "geetest_validate":"ec14f45cc7b18669ae4e3ff2341b13ea"}
     */
    @Override
    public void onDialogResult(String result) {
        GWLog.e(TAG, "GT3BaseListener-->onDialogResult-->" + result);
        try {
            JSONObject json = new JSONObject(result);
            geetest_challenge = json.optString("geetest_challenge", "");
            geetest_seccode = json.optString("geetest_seccode", "");
            geetest_validate = json.optString("geetest_validate", "");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        gt3GeetestUtils.dismissGeetestDialog();
        if (this.result != null){
            this.result.success();
        }
        // 开启api2逻辑
//        new RequestAPI2().execute(result);
    }

    /**
     * 统计信息，参考接入文档
     * @param result
     */
    @Override
    public void onStatistics(String result) {
        GWLog.e(TAG, "GT3BaseListener-->onStatistics-->" + result);
    }

    /**
     * 验证码被关闭
     * @param num 1 点击验证码的关闭按钮来关闭验证码, 2 点击屏幕关闭验证码, 3 点击返回键关闭验证码
     */
    @Override
    public void onClosed(int num) {
        GWLog.e(TAG, "GT3BaseListener-->onClosed-->" + num);
    }

    /**
     * 验证成功回调
     * @param result
     */
    @Override
    public void onSuccess(String result) {
        GWLog.e(TAG, "GT3BaseListener-->onSuccess-->" + result);
        if (this.result != null) {
            this.result.success();
        }
    }

    /**
     * 验证失败回调
     * @param errorBean 版本号，错误码，错误描述等信息
     */
    @Override
    public void onFailed(GT3ErrorBean errorBean) {
        GWLog.e(TAG, "GT3BaseListener-->onFailed-->" + errorBean.toString());
    }

    /**
     * 自定义api1回调
     */
    @Override
    public void onButtonClick() {
        new RequestAPI().execute();
    }

    /**
     * 请求api1
     */
    class RequestAPI extends AsyncTask<Void, Void, JSONObject> {

        @Override
        protected JSONObject doInBackground(Void... params) {
            JSONObject jsonObject = null;
            try {
                String result = NetRequestUtils.requestGet(GWConstant.getInstance().getJiyanInit());
                jsonObject = new JSONObject(result);
            } catch (Exception e) {
                e.printStackTrace();
            }
            return jsonObject;
        }

        @Override
        protected void onPostExecute(JSONObject params) {
            // SDK可识别格式为
            // {"success":1,"challenge":"06fbb267def3c3c9530d62aa2d56d018","gt":"019924a82c70bb123aae90d483087f94","new_captcha":true}
            // TODO 设置返回api1数据，即使为 null 也要设置，SDK内部已处理
            gt3ConfigBean.setApi1Json(params);
            // 继续验证
            gt3GeetestUtils.getGeetest();
        }
    }


    public interface GeetestResult{
        void success();
    }
}
